import 'package:flutter/material.dart';
import 'package:moonmate/theme/app_theme.dart';
import 'dart:math' as math;


const double kCardBorderRadius = 12.0;
const double kPadding = 16.0;
const double kCardPadding = 20.0;
const Size kCycleDiagramSize = Size(200, 200);


class CycleDiagramPainter extends CustomPainter {
  
  static const double kRadiusOffset = 20.0;
  static const double kStrokeWidth = 30.0;
  static const double kOvulationMarkRadius = 30.0;
  
  
  static final TextStyle _textStyle = TextStyle(
    color: AppTheme.textPrimary,
    fontSize: 12,
    fontWeight: FontWeight.bold,
  );
  
  
  void _drawLabel(Canvas canvas, Offset center, String text, Offset offset) {
    final textSpan = TextSpan(text: text, style: _textStyle);
    final textPainter = TextPainter(
      text: textSpan,
      textAlign: TextAlign.center,
      textDirection: TextDirection.ltr,
    );
    textPainter.layout();
    textPainter.paint(
      canvas,
      Offset(
        center.dx - textPainter.width / 2 + offset.dx,
        center.dy - textPainter.height / 2 + offset.dy,
      ),
    );
  }
  
  @override
  void paint(Canvas canvas, Size size) {
    final center = Offset(size.width / 2, size.height / 2);
    final radius = size.width / 2 - kRadiusOffset;
    
    
    void drawArcSegment(double startAngle, double sweepAngle, Color color) {
      final paint = Paint()
        ..color = color
        ..style = PaintingStyle.stroke
        ..strokeWidth = kStrokeWidth;
      canvas.drawArc(
        Rect.fromCircle(center: center, radius: radius),
        startAngle,
        sweepAngle,
        false,
        paint,
      );
    }
    
    
    drawArcSegment(0, 1.2, const Color(0xFFFFF5E6)); 

    drawArcSegment(1.2, 0.8, const Color(0xFFFEE4E4)); 

    drawArcSegment(2.0, 1.5, const Color(0xFFE8F5E9)); 

    drawArcSegment(3.5, 0.7, const Color(0xFFE1F5FE)); 

    
    
    _drawLabel(canvas, center, '月经期', const Offset(60, -80));
    _drawLabel(canvas, center, '卵泡期', const Offset(-80, 20));
    _drawLabel(canvas, center, '排卵期', const Offset(0, -90));
    _drawLabel(canvas, center, '黄体期', const Offset(80, 40));
    
    
    const double ovulationAngle = 3.8;
    final ovulationDotX = center.dx + (radius - kOvulationMarkRadius) * math.cos(ovulationAngle);
    final ovulationDotY = center.dy + (radius - kOvulationMarkRadius) * math.sin(ovulationAngle);
    
    canvas.drawCircle(
      Offset(ovulationDotX, ovulationDotY),
      12,
      Paint()..color = const Color(0xFFE1F5FE),
    );
    canvas.drawCircle(
      Offset(ovulationDotX, ovulationDotY),
      8,
      Paint()..color = AppTheme.secondaryColor,
    );
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return false; 

  }
}


class PointerPainter extends CustomPainter {
  
  static const double kRadiusOffset = 20.0;
  static const double kPeriodAngle = 1.6; 

  static const double kDotAngleStep = 0.15;
  
  @override
  void paint(Canvas canvas, Size size) {
    final center = Offset(size.width / 2, size.height / 2);
    final radius = size.width / 2 - kRadiusOffset;
    
    
    final pointerPaint = Paint()
      ..color = AppTheme.primaryColor
      ..style = PaintingStyle.stroke
      ..strokeWidth = 3
      ..strokeCap = StrokeCap.round;
    
    final endX = center.dx + radius * math.cos(kPeriodAngle);
    final endY = center.dy + radius * math.sin(kPeriodAngle);
    
    canvas.drawLine(center, Offset(endX, endY), pointerPaint);
    
    
    canvas.drawCircle(
      Offset(endX, endY),
      10,
      Paint()..color = AppTheme.primaryColor,
    );
    canvas.drawCircle(
      Offset(endX, endY),
      6,
      Paint()..color = Colors.white,
    );
    
    
    for (int i = 0; i < 5; i++) {
      final dotAngle = 1.2 + i * kDotAngleStep;
      final dotX = center.dx + radius * math.cos(dotAngle);
      final dotY = center.dy + radius * math.sin(dotAngle);
      
      canvas.drawCircle(
        Offset(dotX, dotY),
        i == 4 ? 8 : 4,
        Paint()..color = i == 4 ? AppTheme.primaryColor : AppTheme.primaryLight,
      );
    }
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return false; 

  }
}


class CardContainer extends StatelessWidget {
  final Widget child;
  final Color backgroundColor;
  final bool hasShadow;
  
  const CardContainer({
    super.key,
    required this.child,
    this.backgroundColor = Colors.white,
    this.hasShadow = true,
  });
  
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(kCardPadding),
      decoration: BoxDecoration(
        color: backgroundColor,
        borderRadius: BorderRadius.circular(kCardBorderRadius),
        boxShadow: hasShadow ? const [
          BoxShadow(
            color: Colors.grey,
            blurRadius: 4,
            spreadRadius: 2,
          ),
        ] : null,
      ),
      child: child,
    );
  }
}


class CardTitle extends StatelessWidget {
  final String title;
  
  const CardTitle({super.key, required this.title});
  
  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Container(
          width: 6,
          height: 20,
          color: AppTheme.primaryColor,
          margin: const EdgeInsets.only(right: 8),
        ),
        Text(
          title,
          style: const TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.bold,
            color: AppTheme.textPrimary,
          ),
        ),
      ],
    );
  }
}

class TodayReportScreen extends StatelessWidget {
  const TodayReportScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppTheme.background,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: AppTheme.primaryColor),
          onPressed: () => Navigator.pop(context),
        ),
        centerTitle: true,
        title: const Text(
          '今日密报',
          style: TextStyle(
            color: AppTheme.primaryColor,
            fontSize: 18,
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(kPadding),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            
            _buildDateSelector(),
            const SizedBox(height: 20),
            
            
            _buildPeriodStatusCard(),
            const SizedBox(height: 20),
            
            
            _buildHealthUpdateCard(),
            const SizedBox(height: 20),
            
            
            _buildSymptomPredictionCard(),
            const SizedBox(height: 20),
            
            
            _buildBloodFlowCard(),
          ],
        ),
      ),
    );
  }

  Widget _buildDateSelector() {
    return CardContainer(
      backgroundColor: Colors.white,
      hasShadow: true,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          _buildDateChip('周二(11月11日)', false),
          _buildDateChip('今天(11月12日)', true),
          _buildDateChip('周四(11月13日)', false),
        ],
      ),
    );
  }

  Widget _buildDateChip(String text, bool isActive) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
      decoration: BoxDecoration(
        color: isActive ? AppTheme.primaryColor : Colors.transparent,
        borderRadius: BorderRadius.circular(16),
      ),
      child: Text(
        text,
        style: TextStyle(
          color: isActive ? Colors.white : AppTheme.textPrimary,
          fontSize: 14,
        ),
      ),
    );
  }

  Widget _buildPeriodStatusCard() {
    return CardContainer(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              const Text(
                '月经期·第7天',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                  color: AppTheme.textPrimary,
                ),
              ),
              IconButton(
                icon: const Icon(Icons.info_outline, color: AppTheme.textSecondary),
                onPressed: () {},
                iconSize: 20,
              ),
            ],
          ),
          const SizedBox(height: 8),
          const Text(
            '预测今天月经走了',
            style: TextStyle(
              fontSize: 14,
              color: AppTheme.textSecondary,
            ),
          ),
          const SizedBox(height: 20),
          _buildCycleDiagram(),
        ],
      ),
    );
  }

  Widget _buildCycleDiagram() {
    return SizedBox(
      height: 240,
      child: Stack(
        alignment: Alignment.center,
        children: [
          
          CustomPaint(
            size: kCycleDiagramSize,
            painter: CycleDiagramPainter(),
          ),
          
          Container(
            width: 100,
            height: 100,
            decoration: const BoxDecoration(
              shape: BoxShape.circle,
              color: Color(0xFFFFDFE4),
            ),
            child: Stack(
              alignment: Alignment.center,
              children: [
                const Icon(
                  Icons.water_drop_outlined,
                  size: 60,
                  color: AppTheme.red,
                ),
                Positioned(
                  bottom: 20,
                  child: Container(
                    width: 12,
                    height: 6,
                    decoration: BoxDecoration(
                      color: AppTheme.red,
                      borderRadius: BorderRadius.circular(3),
                    ),
                  ),
                ),
              ],
            ),
          ),
          
          CustomPaint(
            size: kCycleDiagramSize,
            painter: PointerPainter(),
          ),
        ],
      ),
    );
  }

  Widget _buildHealthUpdateCard() {
    return CardContainer(
      backgroundColor: AppTheme.primaryLight,
      hasShadow: false,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Text(
                 '经期健康度已升级更新',
                 style: TextStyle(
                   fontSize: 16,
                   fontWeight: FontWeight.bold,
                   color: AppTheme.primaryColor,
                 ),
               ),
              const SizedBox(height: 8),
              const Text(
                '查看我的全新月经分析',
                style: TextStyle(
                  fontSize: 14,
                  color: AppTheme.textSecondary,
                ),
              ),
            ],
          ),
          ElevatedButton(
            onPressed: null,
            style: ElevatedButton.styleFrom(
              backgroundColor: AppTheme.primaryColor,
              padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(20),
              ),
            ),
            child: const Text(
              '立即查看',
              style: TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.bold,
                color: Colors.white,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildSymptomPredictionCard() {
    return CardContainer(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const CardTitle(title: '症状预测'),
          const SizedBox(height: 12),
          const Text(
            '经期的后期，你可能会发现自己口味改变，偶尔有身体酸痛，但并不严重。',
            style: TextStyle(
              fontSize: 14,
              color: AppTheme.textSecondary,
              height: 1.5,
            ),
          ),
          const SizedBox(height: 16),
          Row(
            children: [
              _buildSymptomIcon('口味改变', true),
              const SizedBox(width: 40),
              _buildSymptomIcon('身体酸痛', false),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildSymptomIcon(String label, bool isNew) {
    
    IconData getIconForSymptom(String symptom) {
      switch (symptom) {
        case '口味改变':
          return Icons.food_bank_outlined;
        case '身体酸痛':
          return Icons.sick_outlined;
        default:
          return Icons.medical_services_outlined;
      }
    }
    
    return Column(
      children: [
        Stack(
          children: [
            Container(
              width: 60,
              height: 60,
              decoration: BoxDecoration(
                color: AppTheme.primaryLight,
                borderRadius: BorderRadius.circular(30),
              ),
              child: Icon(
                getIconForSymptom(label),
                size: 30,
                color: AppTheme.primaryColor,
              ),
            ),
          if (isNew)
              Positioned(
                top: 0,
                right: 0,
                child: Container(
                  padding: const EdgeInsets.all(4),
                  decoration: BoxDecoration(
                    color: Colors.red,
                    borderRadius: BorderRadius.circular(10),
                  ),
                  child: const Text(
                    'new',
                    style: TextStyle(
                      fontSize: 10,
                      color: Colors.white,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              ),
          ],
        ),
        const SizedBox(height: 8),
        Text(
          label,
          style: const TextStyle(
            fontSize: 12,
            color: AppTheme.textPrimary,
          ),
        ),
      ],
    );
  }

  Widget _buildBloodFlowCard() {
    return CardContainer(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const CardTitle(title: '血量变化'),
          const SizedBox(height: 12),
          const Text(
            '经血量在经期的最后几天通常较少。',
            style: TextStyle(
              fontSize: 14,
              color: AppTheme.textSecondary,
              height: 1.5,
            ),
          ),
          const SizedBox(height: 16),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: List.generate(5, (index) {
              
              final opacity = [0.1, 0.2, 0.3, 0.4, 1.0][index];
              return _buildBloodDroplet(opacity);
            }),
          ),
        ],
      ),
    );
  }

  Widget _buildBloodDroplet(double opacity) {
    return Column(
      children: [
        Opacity(
          opacity: opacity,
          child: const Icon(
            Icons.water_drop_outlined,
            size: 40,
            color: AppTheme.red,
          ),
        ),
      ],
    );
  }
}
